package com.awt.moudle;


import java.awt.*;
import java.awt.event.*;

/**
 * @authoer zsj
 * @date 2023/4/17 11:08
 */
public class MenuDemo {

    private Frame frame = new Frame();

    Panel panel = new Panel();

    //创建菜单条
    MenuBar menuBar = new MenuBar();

    //item
    Menu file = new Menu("文件");
    Menu edit = new Menu("编辑");
    Menu format = new Menu("格式");

    MenuItem auto = new MenuItem("自动换行");
    MenuItem copy = new MenuItem("复制");
    MenuItem paste = new MenuItem("粘贴");

    PopupMenu popupMenu = new PopupMenu();

    MenuItem save = new MenuItem("保存");

    MenuItem comment = new MenuItem("注释",
            new MenuShortcut(KeyEvent.VK_Q, true));//关联快捷键

    MenuItem cancel_comment = new MenuItem("取消注释");

    TextArea textArea = new TextArea(6, 40);

    void init() {
        comment.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.append(e.getActionCommand());
            }
        });
        format.add(comment);
        format.add(cancel_comment);

        edit.add(auto);
        edit.add(copy);
        edit.add(paste);
        edit.add(format);
        popupMenu.add(comment);
        popupMenu.add(cancel_comment);
        popupMenu.add(copy);
        popupMenu.add(save);

        menuBar.add(file);
        menuBar.add(edit);
        panel.add(popupMenu);
        panel.setPreferredSize(new Dimension(400, 300));

        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    //显示菜单
                    popupMenu.show(panel, e.getX(), e.getY());
                }
            }
        });
        frame.add(textArea, BorderLayout.SOUTH);
        frame.setMenuBar(menuBar);
        frame.add(panel);


        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new MenuDemo().init();
    }
}
